import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { OtherWarehousingService, SelectOption } from './other-warehousing.service';
import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ToasterService } from '@abp/ng.theme.shared';
import { GoodsSelectDialogComponent } from '../customergoods/goods-select-dialog.component';

@Component({
  selector: 'app-other-warehousing-create',
  template: `
    <div class="modal-header">
      <h3 class="modal-title"><i class="fas fa-plus-circle me-2"></i>预约通知</h3>
      <button type="button" class="btn-close" aria-label="Close" (click)="modal.dismiss()"></button>
    </div>
    <div class="modal-body">
      <form #form="ngForm" class="modern-form">
        <!-- 基本信息 -->
        <div class="section-title mb-3">
          <i class="fas fa-info-circle me-2"></i>基本信息
        </div>
        <div class="row">
          <div class="col-md-3">
            <div class="form-group">
              <label class="required">通知单号</label>
              <input type="text" class="form-control" [(ngModel)]="model.orderNo" name="orderNo" placeholder="请输入通知单号">
            </div>
          </div>
          <div class="col-md-3">
            <div class="form-group">
              <label class="required">货主编码</label>
              <input type="text" class="form-control" [(ngModel)]="model.ownerCode" name="ownerCode" placeholder="请输入货主编码">
            </div>
          </div>
          <div class="col-md-3">
            <div class="form-group">
              <label class="required">货主</label>
              <select class="form-control" [(ngModel)]="model.shipper" name="shipper">
                <option value="">--请选择--</option>
                <option value="OWNER1">货主1</option>
                <option value="OWNER2">货主2</option>
                <option value="OWNER3">货主3</option>
              </select>
            </div>
          </div>
          <div class="col-md-3">
            <div class="form-group">
              <label>预计到货时间</label>
              <input type="datetime-local" class="form-control" [(ngModel)]="model.estimatedArrivalTime" name="estimatedArrivalTime">
            </div>
          </div>
        </div>

        <!-- 订单信息 -->
        <div class="section-title mb-3 mt-4">
          <i class="fas fa-file-alt me-2"></i>订单信息
        </div>
        <div class="row">
          <div class="col-md-3">
            <div class="form-group">
              <label>客户订单号</label>
              <input type="text" class="form-control" [(ngModel)]="model.customerOrderNo" name="customerOrderNo" placeholder="请输入客户订单号">
            </div>
          </div>
          <div class="col-md-3">
            <div class="form-group">
              <label>运输编号</label>
              <input type="text" class="form-control" [(ngModel)]="model.transportNo" name="transportNo" placeholder="请输入运输编号">
            </div>
          </div>
          <div class="col-md-3">
            <div class="form-group">
              <label>运输公司</label>
              <input type="text" class="form-control" [(ngModel)]="model.transportCompany" name="transportCompany" placeholder="请输入运输公司">
            </div>
          </div>
          <div class="col-md-3">
            <div class="form-group">
              <label>供应商</label>
              <input type="text" class="form-control" [(ngModel)]="model.supplier" name="supplier" placeholder="请输入供应商">
            </div>
          </div>
        </div>

        <!-- 仓储信息 -->
        <div class="section-title mb-3 mt-4">
          <i class="fas fa-warehouse me-2"></i>仓储信息
        </div>
        <div class="row">
          <div class="col-md-3">
            <div class="form-group">
              <label>预约库区</label>
              <select class="form-control" [(ngModel)]="model.reservedWarehouseArea" name="reservedWarehouseArea">
                <option [ngValue]="null">--请选择--</option>
                <option *ngFor="let area of warehouseAreas" [ngValue]="area.id">{{area.name}}</option>
              </select>
            </div>
          </div>
          <div class="col-md-3">
            <div class="form-group">
              <label>仓库</label>
              <select class="form-control" [(ngModel)]="model.warehouse" name="warehouse">
                <option [ngValue]="null">--请选择--</option>
                <option *ngFor="let wh of warehouses" [ngValue]="wh.id">{{wh.name}}</option>
              </select>
            </div>
          </div>
          <div class="col-md-3">
            <div class="form-group">
              <label>订单类型</label>
              <select class="form-control" [(ngModel)]="model.orderType" name="orderType">
                <option [ngValue]="null">--请选择--</option>
                <option *ngFor="let type of orderTypes" [ngValue]="type.value">{{type.name}}</option>
              </select>
            </div>
          </div>
          <div class="col-md-3">
            <div class="form-group">
              <label>月台</label>
              <select class="form-control" [(ngModel)]="model.platform" name="platform">
                <option [ngValue]="null">--请选择--</option>
                <option *ngFor="let p of platforms" [ngValue]="p.value">{{p.name}}</option>
              </select>
            </div>
          </div>
        </div>

        <!-- 运输信息 -->
        <div class="section-title mb-3 mt-4">
          <i class="fas fa-truck me-2"></i>运输信息
        </div>
        <div class="row">
          <div class="col-md-3">
            <div class="form-group">
              <label>车号</label>
              <input type="text" class="form-control" [(ngModel)]="model.carNo" name="carNo" placeholder="请输入车号">
            </div>
          </div>
          <div class="col-md-3">
            <div class="form-group">
              <label>司机</label>
              <input type="text" class="form-control" [(ngModel)]="model.driverName" name="driverName" placeholder="请输入司机姓名">
            </div>
          </div>
          <div class="col-md-3">
            <div class="form-group">
              <label>司机电话</label>
              <input type="text" class="form-control" [(ngModel)]="model.driverPhone" name="driverPhone" placeholder="请输入司机电话">
            </div>
          </div>
          <div class="col-md-3">
            <div class="form-group">
              <label>箱注</label>
              <input type="text" class="form-control" [(ngModel)]="model.remark" name="remark" placeholder="请输入箱注">
            </div>
          </div>
        </div>

        <!-- 附件上传 -->
        <div class="section-title mb-3 mt-4">
          <i class="fas fa-paperclip me-2"></i>附件信息
        </div>
        <div class="row">
          <div class="col-md-12">
            <div class="file-upload-area" (click)="fileInput.click()">
              <input #fileInput type="file" class="d-none" (change)="onFileSelected($event)">
              <div class="upload-icon">
                <i class="fas fa-cloud-upload-alt"></i>
              </div>
              <div class="upload-text">
                点击或拖拽文件到此处上传
                <div class="text-muted small mt-1">支持的文件格式：PDF、Word、Excel</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 入库明细 -->
        <div class="section-title mb-3 mt-4">
          <i class="fas fa-list me-2"></i>入库明细
        </div>
        <div class="table-responsive">
          <table class="table modern-table">
            <thead>
              <tr>
                <th>序号</th>
                <th>操作</th>
                <th>商品编码</th>
                <th>商品名称</th>
                <th>数量</th>
                <th>计划占用储位数</th>
                <th>收货完成</th>
              </tr>
            </thead>
            <tbody>
              <tr *ngFor="let item of model.items; let i = index">
                <td>{{i + 1}}</td>
                <td>
                  <div class="form-check">
                    <input type="checkbox" class="form-check-input" [(ngModel)]="item.selected" [name]="'selected' + i">
                  </div>
                </td>
                <td>
                  <div class="input-group">
                    <input type="text" class="form-control" [(ngModel)]="item.productCode" [name]="'productCode' + i" readonly>
                    <button class="btn btn-outline-secondary" type="button" (click)="openGoodsSelect(i)">
                      <i class="fas fa-search"></i>
                    </button>
                  </div>
                </td>
                <td>
                  <input type="text" class="form-control" [(ngModel)]="item.productName" [name]="'productName' + i" readonly>
                </td>
                <td>
                  <input type="number" class="form-control" [(ngModel)]="item.quantity" [name]="'quantity' + i">
                </td>
                <td>
                  <input type="number" class="form-control" [(ngModel)]="item.plannedStorageSlots" [name]="'plannedStorageSlots' + i">
                </td>
                <td>
                  <div class="btn-group" role="group">
                    <input type="radio" class="btn-check" [name]="'status' + i" [id]="'yes' + i" [value]="'Yes'" [(ngModel)]="item.status">
                    <label class="btn btn-outline-success" [for]="'yes' + i">是</label>

                    <input type="radio" class="btn-check" [name]="'status' + i" [id]="'no' + i" [value]="'No'" [(ngModel)]="item.status">
                    <label class="btn btn-outline-danger" [for]="'no' + i">否</label>

                    <input type="radio" class="btn-check" [name]="'status' + i" [id]="'initial' + i" [value]="'Initial'" [(ngModel)]="item.status">
                    <label class="btn btn-outline-secondary" [for]="'initial' + i">初始</label>
                  </div>
                </td>
              </tr>
              <tr class="table-info">
                <td colspan="4" class="text-end"><strong>合计：</strong></td>
                <td><strong>{{totalQuantity}}</strong></td>
                <td><strong>{{totalStorageSlots}}</strong></td>
                <td></td>
              </tr>
            </tbody>
          </table>
          <div class="btn-group">
            <button type="button" class="modern-btn btn-secondary" (click)="addItem()">
              <i class="fas fa-plus"></i>
              <span>添加行</span>
            </button>
            <button type="button" class="modern-btn btn-danger" (click)="removeSelectedItems()">
              <i class="fas fa-trash"></i>
              <span>删除选中</span>
            </button>
            <button type="button" class="modern-btn btn-info" (click)="calculateTotal()">
              <i class="fas fa-calculator"></i>
              <span>合计</span>
            </button>
          </div>
        </div>
      </form>
    </div>
    <div class="modal-footer">
      <button type="button" class="modern-btn btn-secondary" (click)="modal.dismiss()">
        <i class="fas fa-times"></i>
        <span>取消</span>
      </button>
      <button type="button" class="modern-btn btn-primary" (click)="save()">
        <i class="fas fa-save"></i>
        <span>保存</span>
      </button>
    </div>
  `,
  standalone: true,
  imports: [CommonModule, FormsModule, GoodsSelectDialogComponent],
  styleUrls: ['../shared/purchase.styles.scss'],
  styles: [
    `
    .section-title {
      color: var(--bs-primary);
      font-weight: 600;
      font-size: 1.1rem;
      padding-bottom: 0.5rem;
      border-bottom: 1px solid var(--bs-border-color);
    }

    .btn-check:checked + .btn-outline-success {
      background-color: var(--bs-success);
      color: white;
    }

    .btn-check:checked + .btn-outline-danger {
      background-color: var(--bs-danger);
      color: white;
    }

    .btn-check:checked + .btn-outline-secondary {
      background-color: var(--bs-secondary);
      color: white;
    }
    `
  ]
})
export class OtherWarehousingCreateComponent implements OnInit {
  model: any = {
    items: []
  };

  totalQuantity: number = 0;
  totalStorageSlots: number = 0;

  orderTypes: SelectOption[] = [];
  platforms: SelectOption[] = [];
  warehouseAreas: SelectOption[] = [];
  warehouses: SelectOption[] = [];

  constructor(
    private service: OtherWarehousingService,
    public modal: NgbActiveModal,
    private toaster: ToasterService,
    private modalService: NgbModal
  ) { }

  ngOnInit(): void {
    this.loadDropdowns();
    this.addItem();
  }

  calculateTotal() {
    this.totalQuantity = this.model.items.reduce((sum: number, item: any) => {
      return sum + (Number(item.quantity) || 0);
    }, 0);

    this.totalStorageSlots = this.model.items.reduce((sum: number, item: any) => {
      return sum + (Number(item.plannedStorageSlots) || 0);
    }, 0);

    // 显示合计结果
    this.toaster.success(`数量合计: ${this.totalQuantity}, 计划占用储位数合计: ${this.totalStorageSlots}`);
  }

  loadDropdowns() {
    // 加载订单类型
    this.service.getOrderTypes().subscribe({
      next: (response) => {
        console.log('订单类型数据:', response);
        this.orderTypes = response.items || [];
      },
      error: (error) => {
        console.error('加载订单类型失败:', error);
        this.toaster.error('加载订单类型失败');
      }
    });

    // 加载月台
    this.service.getPlatforms().subscribe({
      next: (response) => {
        console.log('月台数据:', response);
        this.platforms = response.items || [];
      },
      error: (error) => {
        console.error('加载月台失败:', error);
        this.toaster.error('加载月台失败');
      }
    });

    // 加载预约库区
    this.service.getWarehouseAreas().subscribe({
      next: (response) => {
        console.log('预约库区数据:', response);
        this.warehouseAreas = response.items || [];
      },
      error: (error) => {
        console.error('加载预约库区失败:', error);
        this.toaster.error('加载预约库区失败');
      }
    });

    // 加载仓库
    this.service.getWarehouses().subscribe({
      next: (response) => {
        console.log('仓库数据:', response);
        this.warehouses = response.items || [];
      },
      error: (error) => {
        console.error('加载仓库失败:', error);
        this.toaster.error('加载仓库失败');
      }
    });
  }

  openGoodsSelect(index: number) {
    const modalRef = this.modalService.open(GoodsSelectDialogComponent, { size: 'lg' });
    modalRef.result.then(
      (result) => {
        if (result) {
          this.model.items[index].productCode = result.productCode;
          this.model.items[index].productName = result.productName;
          this.model.items[index].sku = result.sku;
          this.model.items[index].barcode = result.barcode;
          this.model.items[index].specification = result.specification;
          this.model.items[index].brand = result.brand;
        }
      },
      () => {} // 用户取消选择
    );
  }

  addItem() {
    this.model.items.push({
      productCode: '',
      productName: '',
      quantity: null,
      plannedStorageSlots: null,
      status: 'Initial',
      selected: false
    });
  }

  removeSelectedItems() {
    this.model.items = this.model.items.filter(item => !item.selected);
  }

  onFileSelected(event: any) {
    const file = event.target.files[0];
    if (file) {
      // 处理文件上传
      this.model.attachmentPath = file.name;
    }
  }

  validate(): boolean {
    // 验证通知单号
    if (!this.model.orderNo) {
      this.toaster.error('通知单号为必填项！');
      return false;
    }

    // 验证货主编码
    if (!this.model.ownerCode) {
      this.toaster.error('货主编码为必填项！');
      return false;
    }

    // 验证货主
    if (!this.model.shipper) {
      this.toaster.error('货主为必填项！');
      return false;
    }

    // ... rest of validation ...

    return true;
  }

  save() {
    if (this.validate()) {
      // 移除选中标记
      this.model.items.forEach(item => {
        delete item.selected;
      });

      // 设置主表状态
      const allYes = this.model.items.every(item => item.status === 'Yes');
      const anyNo = this.model.items.some(item => item.status === 'No');
      if (allYes) {
        this.model.status = '已完成';
      } else if (anyNo) {
        this.model.status = '计划中';
      } else {
        this.model.status = '初始状态';
      }

      this.service.create(this.model).subscribe({
        next: (response) => {
          this.toaster.success('保存成功');
          // 触发刷新
          this.service.triggerRefresh();
          // 返回成功标志和数据
          this.modal.close({ success: true, data: response });
        },
        error: (error) => {
          console.error('保存失败:', error);
          this.toaster.error('保存失败');
        }
      });
    }
  }
} 